package com.weixin.paleituo.activity;

import android.Manifest;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.util.Log;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UserInfoBean;
import com.weixin.paleituo.bean.VersionBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.VersionEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.AesUtil;
import com.weixin.paleituo.util.CheckPermission;
import com.weixin.paleituo.util.DeviceUuidFactory;
import com.weixin.paleituo.util.FileUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.PreferencesUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AppVersionUpdate;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Set;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class FlashActivity extends BaseActivity {

    public static final String SP_WELCOME_TAG = "sp_welcome_tag";

    private String mType;
    private String mStringExtra;
    private AppVersionUpdate mAppVersionUpdate;
    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE,  //读取权限
            Manifest.permission.CAMERA,//相机
            Manifest.permission.RECORD_AUDIO,//相机
            Manifest.permission.ACCESS_COARSE_LOCATION,//定位
            Manifest.permission.ACCESS_FINE_LOCATION,//定位
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE

    };
    private ConstraintLayout mConstraintLayout;

    @Override
    protected void initView() {


        setContentView(R.layout.activity_flash);
        mConstraintLayout = findViewById(R.id.constrainlayout);
    }

    private void checiVersion(){

        int versionCode = UIUtils.getVersionCode(this);
        LogUtils.i(TAG,"当前版本号 ："+versionCode);
        Observable<StatusCode<VersionBean>> versionObservable = ApiUtils.getApi().checkVersion(versionCode + "");
        HttpUtil.getInstance().toSubscribe(versionObservable, new ProgressSubscriber<VersionBean>(FlashActivity.this) {

            @Override
            protected void _onNext(StatusCode<VersionBean> t) {
                VersionBean      mVersionBean = t.getData();
                if (mVersionBean !=null){
                    LogUtils.i(TAG,""+ mVersionBean.toString());
                    String coerce = mVersionBean.getCoerce();
                    LogUtils.i(TAG,"是否强制更新 ："+coerce);
                    if (!StringUtils.isEmpty(coerce) &&coerce.equals("1")){
                        //强制更新
                        //检查版本更新

                        mAppVersionUpdate.checkVersionUpdate(true);

                    }else if (!StringUtils.isEmpty(coerce)&& coerce.equals("0")){
                        //非强制
                        //检查版本更新
                        mAppVersionUpdate.checkVersionUpdate(true);

                    }else {
                        //不更新
                        ToastUtils.makeText("当前已是最新版本，无需更新");
                        initPerssionData();
                        }
                    }
            }
            @Override
            protected void _onError(String message) {

                //错误 去登录
/*
                LoginActivity.startActivity(FlashActivity.this,false);
                finish();*/
                initPerssionData();

            }},"",lifecycleSubject,false,true);

    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mAppVersionUpdate = new AppVersionUpdate(FlashActivity.this, mConstraintLayout, lifecycleSubject);
        mType = getIntent().getStringExtra(Contans.INTENT_DATA);
        mStringExtra = getIntent().getStringExtra(Contans.INTENT_EXTRA);


        if (!UIUtils.isMarshmallow()) {
            creatDir();
            checiVersion();
        } else {
            CheckPermission checkPermission = new CheckPermission(this);
            if (checkPermission.permissionSet(PERMISSION)) {
                startPermissionActivity();
            } else {
                creatDir();
                checiVersion();
            }
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Contans.PERMISSION_REQUST_COND) {
            if (resultCode == PermissionActivity.PERMISSION_DENIEG) {
                //没有权限
                finish();
            } else if (resultCode == PermissionActivity.PERMISSION_GRANTED) {
                //有权限
                creatDir();
                checiVersion();
            }
        }
    }
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, Contans.PERMISSION_REQUST_COND, PERMISSION);
    }


    /**
     * 更新事件
     * @param versionEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void versionEvent(VersionEvent versionEvent){
        int type = versionEvent.getType();

        if (type==1){
            //更新取消
        initPerssionData();

        }else if (type==3){
         //更新失败
            initPerssionData();
        }

    }


    /**
     * 有权限
     */
    private void initPerssionData() {

      final   String deviceUuid = DeviceUuidFactory.getInstance(this).getDeviceUuid();
        if (PreferencesUtils.getInstance().getBoolean(SP_WELCOME_TAG,true)){
            startActivity(WelcomeActivity.call2WelcomeActivity(this));
            finish();
        } else {
            //免登陆
            final String username = PreferencesUtils.getInstance().getString(Contans.username, "");
            final String password = PreferencesUtils.getInstance().getString(Contans.password, "");

            if (!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password) && NetUtils.NetwrokIsUseful(this)){
                ApiUtils.getApi().login(Contans.isEncrypt?AesUtil.aesEncrypt(username):username,Contans.isEncrypt?AesUtil.aesEncrypt(password):password,deviceUuid).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<StatusCode<UserInfoBean>>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }
                            @Override
                            public void onNext(StatusCode<UserInfoBean> value) {

                                if (value.isFlag()){

                                    BaseApplication.isLoginSuccess=true;
                                    BaseApplication.sUserInfoBean=value.getData();
                                    PreferencesUtils.getInstance().putString(Contans.username,username);
                                    PreferencesUtils.getInstance().putString(Contans.password,password);
                                    if (BaseApplication.sUserInfoBean!=null){
                                        String localAlias = PreferencesUtils.getInstance().getString(Contans.JPUSH_SET_ALIAS, "");
                                        if (!StringUtils.isEmpty(deviceUuid ) && !localAlias.equals(deviceUuid)){
                                            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, deviceUuid));
                                        }
                                    }

                                    if (!StringUtils.isEmpty(mType)){
                                        switch (mType){
                                            case "1":
                                                //系统消息
                                                break;
                                            case "2":
                                                //签约楼市
                                                String id ;
                                                try {
                                                    JSONObject extrasJson = new JSONObject(mStringExtra);
                                                    id = extrasJson.optString("id");
                                                    String username=    extrasJson.optString("username");
                                                    Intent mIntent = new Intent(FlashActivity.this, BuyHouseStepActivity.class);
                                                    mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    mIntent.putExtra(Contans.INTENT_EXTRA,username);
                                                    mIntent.putExtra(Contans.INTENT_DATA, id);
                                                    startActivity(mIntent);
                                                } catch (Exception e) {
                                                    LogUtils.w(TAG, "Unexpected: extras is not a valid json", e);
                                                }
                                                break;
                                            case "3":
                                                //优惠券
                                                CouponsActivity.startActivity(FlashActivity.this);

                                                break;
                                            case "4":

                                                MyMessageActivity.startActivity(FlashActivity.this,BaseApplication.getUserId());

                                                break;


                                            default:
                                                MainActivity.startActivity(FlashActivity.this);
                                                break;
                                        }


                                    }else {
                                        MainActivity.startActivity(FlashActivity.this);

                                    }

                                }else {
                                    LoginActivity.startActivity(FlashActivity.this,false);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                LoginActivity.startActivity(FlashActivity.this,false);
                                finish();
                            }

                            @Override
                            public void onComplete() {
                                finish();

                            }
                        });
            }else {
                //去登陆
                LoginActivity.startActivity(this,false);
                finish();
            }
        }

        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
        builder.statusBarDrawable = R.mipmap.arrow_down;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        // JPushInterface.setPushNotificationBuilder(1, builder);
        JPushInterface.setDefaultPushNotificationBuilder(builder);
    }

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.i(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(BaseApplication.mContext,
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs+alias);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    PreferencesUtils.getInstance().getString(Contans.JPUSH_SET_ALIAS, alias);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
            //ExampleUtil.showToast(logs, getApplicationContext());
        }
    };

public static void  startActivity(Context context,String type,String extra){
    Intent intent=new Intent(context,FlashActivity.class);
    intent.putExtra(Contans.INTENT_DATA,type);
    intent.putExtra(Contans.INTENT_EXTRA,extra);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

            }

    /**
     * 创建目录
     */
    private void creatDir() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            FileUtils.APP_DIR = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/paleituo";
        } else {
            FileUtils.APP_DIR = this.getFilesDir().getAbsolutePath() + "/paleituo";
        }
        FileUtils.APP_LOG = FileUtils.APP_DIR + "/log";
        FileUtils.APP_CRASH = FileUtils.APP_DIR + "/crash";
        FileUtils.APK_DIR = FileUtils.APP_DIR + "/apks";
        FileUtils.IMAGE_DIR = FileUtils.APP_DIR + "/imag";

        File appDir = new File(FileUtils.APP_DIR);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File logDir = new File(FileUtils.APP_LOG);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        File crashDir = new File(FileUtils.APP_CRASH);
        if (!crashDir.exists()) {
            crashDir.mkdirs();
        }
        File apkDir = new File(FileUtils.APK_DIR);
        if (!apkDir.exists()) {
            apkDir.mkdirs();
        }
        File imageDir = new File(FileUtils.IMAGE_DIR);
        if (!imageDir.exists()) {
            imageDir.mkdirs();
        }



        //上传错误日志

        final File logfile=new File(FileUtils.APP_CRASH,"log.txt");

        if (logfile.exists()){

            //
            // FileUtils.APP_CRASH/
            Observable<StatusCode<String>> statusCodeObservable = Observable.just(logfile)
                    .flatMap(new Function<File, ObservableSource<StatusCode<String>>>() {
                        @Override
                        public ObservableSource<StatusCode<String>> apply(File file) throws Exception {
                            InputStream inputStream = new FileInputStream(file);
                            String s = FileUtils.readInStream(inputStream);

                            if (StringUtils.isEmpty(s)) {
                                return Observable.empty();
                            }

                            return ApiUtils.getApi().uploadErrLog(s, 1);
                        }
                    }).subscribeOn(Schedulers.io());

            HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<String>(this) {
                @Override
                protected void _onNext(StatusCode<String> stringStatusCode) {
                    LogUtils.i(TAG,"成功");
                    FileUtils.deleteFile(logfile.getAbsolutePath());
                }

                @Override
                protected void _onError(String message) {

                    LogUtils.i(TAG,"上传错误日志失败");

                }
            },"",lifecycleSubject,false,true);

        }


        //注册微信
       /* WXTextObject wxTextObject=new WXTextObject();
        wxTextObject.text="hehe";

        WXMediaMessage wxMediaMessage=new WXMediaMessage();
        wxMediaMessage.mediaObject=wxTextObject;
        wxMediaMessage.description="haha";

        SendMessageToWX.Req req =new SendMessageToWX.Req();
        req.transaction=String.valueOf(SystemClock.currentThreadTimeMillis());
        req.message=wxMediaMessage;

        IWXAPI wxapi = WXAPIFactory.createWXAPI(this, WXPayEntry.APP_ID);

        wxapi.sendReq(req);*/

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
